<template>
    <div>
        <table border="1">
            <thead>
                <th>序号</th>
                <th>商品</th>
                <th>单价</th>
                <th>数量</th>
                <th>操作</th>
            </thead>
            <tbody>
                <tr v-for="(item,index) in tableData" :key="index">
                    <td>{{index+1}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.price}}</td>
                    <td>
                        <counter :goodsnum="item.num" :index="index" @add="add" @sub="sub" @changeNum="changeNum"></counter>
                    </td>
                    <td>
                        <button>编辑</button>
                        <button @click="handleDelect(index)" :index="index">删除</button>
                    </td>
                </tr>
            </tbody>
        </table>
        <div>
            <h3>总价{{totalPrice}}</h3>
            <h3>总数{{totalNum}}</h3>
        </div>
    </div>
</template>
<script>
import counter from './counter.vue'
import store from '../store.js'
export default {
    data(){
        return {
            tempNum:0,
            tableData: store.state.data
        }
    },
    components:{
        counter
    },
    methods:{
        add(index){
            this.tableData[index].num++;
        },
        sub(index){
            if(this.tableData[index].num>0){
                this.tableData[index].num--;
            }
        },
        changeNum(arr){
            console.log(arr)
            this.tableData[arr[1]].num = arr[0];
        },
        handleDelect(index){
            this.tableData.splice(index,1);
        }
    },
    computed:{
        totalPrice(){
            let price_total = 0;
            this.tableData.forEach(row => {
                price_total += row.num * row.price;
            });
            return price_total.toFixed(2);
        },
        totalNum(){
            let num_total = 0;
            this.tableData.forEach(row => {
                num_total += row.num;
            });
            return num_total;
        },
        
    }
}
</script>